﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using QxFramework.Utilities;

public class BattleManager : MonoSingleton<BattleManager>, IEventListener
{
    /// <summary>
    /// 最小伤害量
    /// </summary>
    public int MinDamage;

    private void Awake()
    {
        Initiate();
    }
    /// <summary>
    /// 初始化方法
    /// </summary>
    public void Initiate()
    {

    }

    private void Start()
    {
        if (EventNodeCore.GetInstance())
        {
            EventNodeCore.GetInstance().AttachEventListener(EventDef.Battle, this);
        }
    }
    private void OnDestroy()
    {
        if (EventNodeCore.GetInstance())
        {
            EventNodeCore.GetInstance().DetachEventListener(EventDef.Battle, this);
        }
    }

    public bool HandleEvent(int id, object param1, object param2)
    {
        switch (id)
        {
            case EventDef.Battle: // 接收发出攻击信号
                BattleStart((CreatureData)param1, (GameObject)param2);
                break;
        }
        return false;
    }
    public int EventPriority() { return 0; }

    /// <summary>
    /// 进入战斗逻辑
    /// </summary>
    /// <param name="BData">攻击发起者</param>
    /// <param name="target">受攻击的目标</param>
    private void BattleStart(CreatureData BData, GameObject target)
    {
        Debug.Log("攻击信号受理");
        CreatureData DefSide = GetTargetData(target);
        int loseHP = DefSide.DEF - BData.ATK;
        if (loseHP > MinDamage) loseHP = MinDamage; // 保证最小伤害量       
        Debug.Log("战斗数值变动: " + BData.gameObject.name + "向" + target.name + "攻击!");
        SendMessage(EventDef.HpChange, loseHP, target);
        SendMessage(-EventDef.Battle, BData, target);
    }
    /// <summary>
    /// 获取目标物体的数值属性
    /// </summary>
    /// <param name="target"></param>
    /// <returns></returns>
    private CreatureData GetTargetData(GameObject target)
    {
        if (target)
        {
            if (target.GetComponent<CreatureData>())
                return target.GetComponent<CreatureData>();
        }
        Debug.LogError("真的是造物吗？？？" + target.name);
        return null;
    }

    private void SendMessage(int massage, object parameter1 = null, object parameter2 = null)
    {
        EventNodeCore.GetInstance().HandleEvent(massage, parameter1, parameter2); // 发送行动消息
    }
}
